package ThreadPool;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class DemoCompletionService {

	private static Callable<String> task1 = new Callable<String>() {

		@Override
		public String call() throws Exception {
			Thread.sleep(2 * 1000);
			System.out.println(Thread.currentThread().getName());
			return "task1";
		}
	};

	private static Callable<String> task2 = new Callable<String>() {

		@Override
		public String call() throws Exception {
			Thread.sleep(5 * 1000);
			return "task2";
		}
	};

	public static void main(String[] args) {

		List<Future<String>> list = new ArrayList<Future<String>>();

		ExecutorService exec = Executors.newFixedThreadPool(2);
		CompletionService<String> service = new ExecutorCompletionService<String>(exec);

		list.add(service.submit(task1));
		list.add(service.submit(task2));

		exec.shutdown();
		exec.shutdownNow(); // 区别
		try {
			for (int i = 0; i < list.size(); i++) {
				Future<String> future = service.take();
				System.out.println(future.get()); // 阻塞在get方法这里
			}
		} catch (InterruptedException e) {
			Thread.currentThread().interrupt();
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		}
		System.out.println("=====");

		System.out.println("list size is:" + list.size());

	}
}
